import {
  reactive,
  watch,  
  computed,
  toRefs,
  nextTick
} from 'vue'
import { useStore } from 'vuex'
import { searchApi } from '@/api'
export default function () {
  const store = useStore()

  const tabs = [
    {
      name: '综合',
      component: 'default',
      params: {},
      children: [
        {
          name: '默认排序',
          component: 'defaultOrder',
          params: {},
          url: '/search/getResult',
          bangumis: [],
          movies: []
        },
        {
          name: '播放多',
          component: 'click',
          params: { order: 'click', search_type: 'video' }
        },
        {
          name: '新发布',
          component: 'pubdate',
          params: { order: 'pubdate', search_type: 'video' }
        },
        {
          name: '弹幕多',
          component: 'dm',
          params: { order: 'dm', search_type: 'video' }
        }
      ]
    },
    {
      name: '番剧',
      component: 'bangumi',
      params: { search_type: 'media_bangumi', order: 'totalrank' }
    },
    {
      name: 'UP主',
      component: 'user',
      params: { search_type: 'bili_user', order: 'totalrank' }
    },
    {
      name: '影视',
      component: 'movies',
      params: { search_type: 'media_ft', order: 'totalrank' }
    }
  ]

  const state = reactive({
    listRef: null,
    currentTab: 'default',
    childCurrentTab: 'defaultOrder',
    tabs: tabs.map((item, index) => {
      return {
        ...item,
        id: index,
        num: 0,
        currentPage: 1,
        pageSize: 20,
        totalPage: 0,
        list: []
      }
    }),
    childTabs: tabs[0].children.map((item, index) => {
      return {
        ...item,
        id: 't' + index,
        currentPage: 1,
        pageSize: 20,
        totalPage: 0,
        list: []
      }
    }),
    currentComponent: computed({
      get() {
        const tabs = ['default', 'bangumi', 'user', 'movies']
        const include = tabs.includes(state.currentTab)
        return include
          ? `SearchResult${state.currentTab.replace(/^\S/, (s) =>
              s.toUpperCase()
            )}`
          : 'SearchResultDefault'
      }
    }),
    currentComponentProps: computed({
      get() {
        let props
        const { bangumis, movies, list, currentPage, pageSize } = getCurrent()
        if (state.currentTab === 'default') {
          props = {
            tabs: state.tabs[0].children,
            currentTab: state.childCurrentTab,
            bangumis: bangumis || [],
            movies: movies || [],
            list: list.slice(0, currentPage * pageSize)
          }
        } else {
          props = {
            list: list.slice(0, currentPage * pageSize)
          }
        }
        return props
      }
    }),
    currentComponentEvents: computed({
      get() {
        let events
        if (state.currentTab === 'default') {
          events = {
            'select-tab': handleTab,
            'select-child-tab': handleChildTab
          }
        } else {
          events = {}
        }
        return events
      }
    })
  })

  const getCurrent = () => {
    let current
    if (state.currentTab === 'default') {
      current = state.childTabs.find(
        (item) => item.component === state.childCurrentTab
      )
    } else {
      current = state.tabs.find((item) => item.component === state.currentTab)
    }
    return current
  }

  const countTabNum = (data) => {
    const topTlist = data.top_tlist
    if (!topTlist) {
      return
    }
    state.tabs.forEach((tab) => {
      const comp = tab.component
      if (comp === 'bangumi') {
        tab.num = topTlist.media_bangumi
      } else if (comp === 'user') {
        tab.num = topTlist.bili_user
      } else if (comp === 'movies') {
        tab.num = topTlist.media_ft
      }
    })
  }

  const getData = async () => {
    try {
      startLoading()
      const current = getCurrent()
      const {
        params,
        currentPage,
        pageSize,
        totalPage,
        list,
        url,
        bangumis,
        movies
      } = current
      const { data } = await searchApi.getSearchResult(
        url || '/search/byKeyword',
        {
          keyword: store.state.search.searchKeyword,
          page: currentPage,
          pagesize: pageSize,
          ...params
        }
      )
      if (data) {
        const { result, numPages, page } = data
        if (totalPage === 0) {
          current.totalPage = numPages
        }

        if (numPages === 0) {
          complete()
        } else if (
          state.currentTab === 'default' &&
          state.childCurrentTab === 'defaultOrder'
        ) {
          countTabNum(data)
          // 综合-默认排序
          // 过滤搜索结果里面的视频 番剧 和影视数据
          const videos = result.find((item) => item.result_type === 'video')
          if (videos) {
            current.list = [...list, ...videos.data]
          }
          const newBangumis = result.find(
            (item) => item.result_type === 'media_bangumi'
          )
          if (newBangumis) {
            current.bangumis = [...bangumis, ...newBangumis.data]
          }
          const newMovies = result.find(
            (item) => item.result_type === 'media_ft'
          )
          if (newMovies) {
            current.movies = [...movies, ...newMovies.data]
          }
        } else if (
          state.currentTab === 'default' &&
          state.childCurrentTab !== 'defaultOrder'
        ) {
          // 综合-默认排序
          current.list = [...list, ...result]
        } else {
          // 设置类型排序的数据
          current.list = [...list, ...result]
        }
        if (page === numPages) {
          complete()
        }
      } else {
        complete()
      }
    } catch (error) {
      console.log(error)
    } finally {
      stopLoading()
    }
  }

  const startLoading = () => {
    state.listRef?.startLoad()
  }
  const stopLoading = () => {
    state.listRef?.stopLoad()
  }
  const complete = () => {
    state.listRef?.completeLoad()
  }
  const isComplete = () => {
    return state.listRef?.isComplete() ?? false
  }
  const reset = () => {
    state.listRef?.reset()
  }

  const handleLoad = () => {
    const current = getCurrent()
    const { totalPage, currentPage } = current
    if (currentPage < totalPage) {
      current.currentPage = currentPage + 1
      getData()
    } else {
      complete()
    }
  }

  const handleTab = (item) => {
    state.currentTab = item.component
    nextTick(() => {
      const { list } = getCurrent()
      if (!list.length) {
        if (isComplete()) {
          reset()
        }
        getData()
      }
    })
  }

  const handleChildTab = (item) => {
    state.childCurrentTab = item.component
    nextTick(() => {
      const { list } = getCurrent()
      if (!list.length) {
        getData()
      }
    })
  }

  watch(
    () => store.state.search.searchKeyword,
    (newVal) => {
      state.currentTab = 'default'
      if (newVal.trim() !== '') {
        getData()
      }
    },
    {
      immediate: true
    }
  )

  return {
    ...toRefs(state),
    handleLoad,
    handleTab
  }
}
